package com.ego.order.controller;

import com.ego.order.pojo.Order;
import com.ego.order.pojo.OrderDetail;
import com.ego.order.service.OrderService;
import com.ego.order.service.PayLogService;
import com.ego.pojo.vo.ResultVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Ares
 * @date 2020-12-11
 */
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Resource
    private PayLogService payLogService;


    /**
     * 创建订单
     * @param order
     * @return
     */
    @PostMapping
    public ResponseEntity<Long> createOrder(@RequestBody Order order) {
        orderService.createOrder(order);
        return ResponseEntity.ok(order.getOrderId());
    }

    /**
     * 生成微信支付链接
     *
     * @param orderId
     * @return
     */
    @ApiOperation(value = "生成微信支付链接",
            notes = "微信支付链接")
    @GetMapping("/url/{id}")
    public ResponseEntity<String> generateUrl(@PathVariable("id") Long orderId) {
        return ResponseEntity.status(HttpStatus.OK).body(orderService.generateUrl(orderId));
    }

    /**
     * 查询订单支付状态
     *
     * @param orderId
     * @return
     */
    @GetMapping("status/{id}")
    @ApiOperation(value = "查询订单支付状态")
    public ResponseEntity<Integer> queryOrderStateByOrderId(@PathVariable("id") Long orderId) {
        return ResponseEntity.ok(payLogService.queryOrderStateByOrderId(orderId));
    }

    @GetMapping("/checkSeckillOrder/{orderId}")
    public ResponseEntity<Boolean> checkSeckillOrder(@PathVariable("orderId") Long orderId) {
        return ResponseEntity.ok(orderService.checkSeckillOrder(orderId));
    }

    @GetMapping("/list")
    public ResponseEntity<ResultVO<Order>> findOrderPage(
            @RequestParam(value = "status",required = false) Integer status,
            @RequestParam("page") Integer page,
            @RequestParam("rows") Integer rows){
        ResultVO<Order> result = null;
        if(status==null) {
            result = orderService.selectOrderPage(page, rows);
        }else{
            result = orderService.selectStatusOrderPage(status,page,rows);
        }
        result.setPage(page);
        result.setRows(rows);
        if(result==null){
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(result);
    }

    @GetMapping("cancel")
    public ResponseEntity<String> cancel(@RequestParam("orderId") Long orderId){
        Integer rows = orderService.cancelOrder(orderId);
        if(rows>0){
            return ResponseEntity.ok("取消成功");
        }
        return ResponseEntity.badRequest().body("取消失败");
    }
}
